package com.luhuiguo.cms.server.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.bradmcevoy.http.AuthenticationHandler;
import com.bradmcevoy.http.AuthenticationService;
import com.bradmcevoy.http.CompressingResponseHandler;
import com.bradmcevoy.http.HttpManager;
import com.bradmcevoy.http.ResourceFactory;
import com.bradmcevoy.http.http11.auth.BasicAuthHandler;
import com.bradmcevoy.http.webdav.DefaultWebDavResponseHandler;
import com.bradmcevoy.http.webdav.WebDavResponseHandler;
import com.ettrema.http.fs.LockManager;
import com.ettrema.http.fs.SimpleLockManager;
import com.luhuiguo.cms.server.web.DavController;
import com.luhuiguo.cms.server.webdav.GaeResourceFactory;
import com.luhuiguo.cms.server.webdav.SpringSecurityManager;

/**
 * The spring java-based configuration for WebDAV.
 * 
 * @author LuHuiguo
 * @version $Id: DavConfig.java 184 2010-05-24 10:51:16Z luhuiguo@gmail.com $
 */
@Configuration
public class DavConfig {

    public static final String DAV_CONTEXT_PATH = "webdav";

    @Bean
    public LockManager lockManager() {
        return new SimpleLockManager();
    }

    @Bean
    public com.bradmcevoy.http.SecurityManager securityManager() {
        return new SpringSecurityManager("LuLu CMS");
    }

    @Bean
    public AuthenticationHandler basicAuthHandler() {
        return new BasicAuthHandler();
    }

    @Bean
    public AuthenticationService authenticationService() {
        List<AuthenticationHandler> authenticationHandlers = new ArrayList<AuthenticationHandler>();
        authenticationHandlers.add(basicAuthHandler());
        return new AuthenticationService(authenticationHandlers);
    }

    @Bean
    public WebDavResponseHandler defaultWebDavResponseHandler() {
        return new DefaultWebDavResponseHandler(authenticationService());
    }

    @Bean
    public WebDavResponseHandler compressingResponseHandler() {
        return new CompressingResponseHandler(defaultWebDavResponseHandler());
    }

    @Bean
    public ResourceFactory gaeResourceFactory() {
        GaeResourceFactory rf = new GaeResourceFactory(securityManager(), DAV_CONTEXT_PATH);
        rf.setLockManager(lockManager());
        // rf.setContextPath(DAV_CONTEXT_PATH);
        rf.setMaxAgeSeconds(315360000L);
        rf.setAllowDirectoryBrowsing(true);

        return rf;
    }

    @Bean
    public HttpManager httpManager() {
        HttpManager httpManager = new HttpManager(gaeResourceFactory(), compressingResponseHandler(),
                authenticationService());
        return httpManager;
    }

    @Bean
    public DavController davController() {
        return new DavController();
    }
}
